package com.davesandoval.tpdroid;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class Httpclient {

	private String[][] allData;
	private String serverURL;

	private static HttpClient httpclient;

	public Httpclient(String globalURI) {
		httpclient = new DefaultHttpClient();
		httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY,
				CookiePolicy.BROWSER_COMPATIBILITY);
		serverURL = globalURI;
		allData = getUsers(serverURL);
	}

	public String doLogin(String globalURI, String logid, String pass)
			throws ClientProtocolException, IOException {
		HttpPost httppost = new HttpPost(globalURI + "processlogin.asp");
		List<NameValuePair> nvp = new ArrayList<NameValuePair>();
		nvp.add(new BasicNameValuePair("logid", logid));
		nvp.add(new BasicNameValuePair("pass", pass));
		nvp.add(new BasicNameValuePair("field1", "login"));
		httppost.setEntity(new UrlEncodedFormEntity(nvp));
		HttpResponse response = httpclient.execute(httppost);

		if (loginFailed(response)) {
			return "LoginFailed";
		} else {
			return "LoginSuccess";
		}
	}

	public String[][] checkOpen(String globalURI)
			throws ClientProtocolException, IOException {
		String url = globalURI + "checkopen.asp";
		String rawdata = getContent(url);
		String viewso = rawdata.substring(
				rawdata.indexOf("<table border=1>") + 500,
				rawdata.indexOf("</table>"));
		viewso = viewso
				.replaceAll(
						"<td nowrap valign=top><font face=\"verdana\" size=2><b>\n",
						"");
		viewso = viewso
				.replaceAll(
						"<a title=\"view this service order\" href=\"javascript:viewso",
						"");
		viewso = viewso.replaceAll("\">\n", "~");
		viewso = viewso
				.replaceAll(
						"</a></b>&nbsp;</font><font face=\"verdana\" size=1></font></td>\n<td nowrap><font face='verdana' size=2>&nbsp;",
						"~");
		viewso = viewso
				.replaceAll(
						"</b>&nbsp;</font></td><td><font face='verdana' size=2>&nbsp;</b>&nbsp;",
						"~");
		viewso = viewso.replaceAll(
				"</font></td><td nowrap><font face='verdana' size=2>&nbsp;",
				"~");
		viewso = viewso.replaceAll("</b>&nbsp;</font></td></tr>", "~");
		viewso = viewso.replaceAll("</b>&nbsp;", "");
		viewso = viewso.replaceAll("<tr>", "");
		viewso = viewso.replaceAll("\n", "");

		String[] soSplit = viewso.split("~");
		String[][] soData = new String[soSplit.length / 7][6];

		int increment = 1;
		for (int i = 0; i < soData.length; i++) {
			for (int j = 0; j < 6; j++) {
				soData[i][j] = soSplit[increment];
				increment++;
				if (increment % 7 == 0) {
					increment++;
				}
			}
		}
		return soData;
	}

	public String getContent(String url) throws ClientProtocolException,
			IOException {
		HttpGet httpget = new HttpGet(url);
		HttpResponse response = httpclient.execute(httpget);

		String result = null;
		BufferedReader in = null;
		in = new BufferedReader(new InputStreamReader(response.getEntity()
				.getContent()));

		StringBuffer sb = new StringBuffer("");
		String line = "";
		String NL = System.getProperty("line.separator");
		while ((line = in.readLine()) != null) {
			sb.append(line + NL);
		}
		in.close();

		result = sb.toString();
		return result;
	}

	public String[] getUserId(String globalURI) {
		String[] result = new String[allData.length];
		for (int i = 0; i < result.length; i++) {
			result[i] = allData[i][0];
		}
		return result;
	}

	public String[] getUser(String globalURI) {
		String[] result = new String[allData.length];
		for (int i = 0; i < result.length; i++) {
			result[i] = allData[i][1];
		}
		return result;
	}

	public String[][] getUsers(String globalURI) {
		String url = globalURI + "employeelogin.asp";

		String str = null;

		try {
			str = getContent(url);

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String concat = str.substring(str.indexOf("<select name=") + 81,
				str.indexOf("</select>"));

		concat = concat.replaceAll("&nbsp;", "");
		concat = concat.replaceAll("&", "");
		concat = concat.replaceAll("</option>", "~");
		concat = concat.replaceAll("<option value=", "");
		concat = concat.replaceAll(">", "~");
		concat = concat.replaceAll("<option", "");
		concat = concat.replaceAll("\t", "");
		concat = concat.replace("\r\n", "~");
		concat = concat.replace("\n", "");
		concat = concat.replace("/option", "");
		concat = concat.replace("~110", "~~110");
		String[] users = concat.split("~");

		String[][] result = new String[users.length / 2][2];
		int increment = 0;
		for (int i = 0; i < result.length; i++) {
			for (int j = 0; j < 2; j++) {
				result[i][j] = users[increment];
				increment++;
			}
		}
		return result;
	}

	public void putBatchSO(String soNumber, String newStatus, String soReason,
			String logComment, String startDate, String endDate,
			String startTime, String endTime, String workRequested,
			String workPerformed, String chargeable, String billable,
			String copylc, String blntask, String accountNum,
			String strRateBasis) throws ClientProtocolException, IOException {

		String modStartTime = startTime.replaceAll("PM", " PM");
		String modEndTime = endTime.replaceAll("PM", " PM");
		modStartTime = modStartTime.replaceAll("AM", " AM");
		modEndTime = modEndTime.replaceAll("AM", " AM");
		Integer intRateBasis = strRateBasis.contentEquals("Account Default") ? 3
				: 4;

		Date start = new Date(Date.parse(startDate + " " + modStartTime));
		Date end = new Date(Date.parse(endDate + " " + modEndTime));

		Calendar calStart = Calendar.getInstance();
		Calendar calEnd = Calendar.getInstance();
		calStart.setTime(start);
		calEnd.setTime(end);

		Integer hours = 0;
		Integer minutes = 0;
		long elapsedDays = calEnd.getTimeInMillis()
				- calStart.getTimeInMillis();
		hours = (int) (elapsedDays / (60 * 60 * 1000));
		minutes = (int) ((elapsedDays / (60 * 1000)) - hours * 60);

		String numloghours = hours.toString();
		String numlogminutes = minutes.toString();
		String numelapsedhours = numloghours;
		String numelapsedminutes = numlogminutes;

		System.out.println("Posting to SO# " + soNumber);
		HttpPost httppost = new HttpPost(serverURL + "editcall5.asp?select1="
				+ soNumber);
		List<NameValuePair> nvp = new ArrayList<NameValuePair>();
		nvp.add(new BasicNameValuePair("empid", Main.username));
		nvp.add(new BasicNameValuePair("numtech", Main.logid));
		nvp.add(new BasicNameValuePair("numsonumber", soNumber));
		nvp.add(new BasicNameValuePair("callogstartdate", startDate));
		nvp.add(new BasicNameValuePair("calenddate", endDate));
		nvp.add(new BasicNameValuePair("colLogComment", logComment));
		nvp.add(new BasicNameValuePair("coltimelogreason", soReason));
		nvp.add(new BasicNameValuePair("intratebasis", intRateBasis.toString()));
		nvp.add(new BasicNameValuePair("numaccountnumber", accountNum));
		nvp.add(new BasicNameValuePair("stat", newStatus));
		nvp.add(new BasicNameValuePair("callogstarttime", startTime));
		nvp.add(new BasicNameValuePair("calendtime", endTime));

		nvp.add(new BasicNameValuePair("numloghours", numloghours));
		nvp.add(new BasicNameValuePair("numlogminutes", numlogminutes));
		nvp.add(new BasicNameValuePair("numelapsedhours", numelapsedhours));
		nvp.add(new BasicNameValuePair("numelapsedminutes", numelapsedminutes));

		nvp.add(new BasicNameValuePair("workrequested", workRequested));
		nvp.add(new BasicNameValuePair("workperformed", workPerformed));
		nvp.add(new BasicNameValuePair("numMileage", "0"));
		nvp.add(new BasicNameValuePair("colParking", "0.00"));
		nvp.add(new BasicNameValuePair("colTolls", "0.00"));
		nvp.add(new BasicNameValuePair("colFuel", "0.00"));
		nvp.add(new BasicNameValuePair("colAccomodations", "0.00"));
		nvp.add(new BasicNameValuePair("colMeals", "0.00"));
		nvp.add(new BasicNameValuePair("colMiscExpenses", "0.00"));
		nvp.add(new BasicNameValuePair("numchargeable", chargeable));
		nvp.add(new BasicNameValuePair("numbillable", billable));
		nvp.add(new BasicNameValuePair("copylc", copylc));
		nvp.add(new BasicNameValuePair("blntask", blntask));
		nvp.add(new BasicNameValuePair("strratebasis", strRateBasis));

		httppost.setEntity(new UrlEncodedFormEntity(nvp));
		HttpResponse response = httpclient.execute(httppost);

		BufferedReader in = null;
		in = new BufferedReader(new InputStreamReader(response.getEntity()
				.getContent()));

		StringBuffer sb = new StringBuffer("");
		String line = "";
		String NL = System.getProperty("line.separator");
		while ((line = in.readLine()) != null) {
			sb.append(line + NL);
		}
		in.close();

		String result = sb.toString();

		// System.out.println(result);

		if (result.contains("Sorry, you chose an invalid log rate basis")) {
			putBatchSO(soNumber, newStatus, soReason, logComment, startDate,
					endDate, modStartTime, modEndTime, workRequested,
					workPerformed, chargeable, billable, copylc, blntask,
					accountNum, "Account Default");
		}
	}

	public String[] getSODetail(String soNum) throws ClientProtocolException,
			IOException {
		HttpPost httppost = new HttpPost(serverURL + "updatecall2.asp");
		List<NameValuePair> nvp = new ArrayList<NameValuePair>();
		nvp.add(new BasicNameValuePair("hidd1", soNum));
		nvp.add(new BasicNameValuePair("hidd2", "0"));
		httppost.setEntity(new UrlEncodedFormEntity(nvp));
		HttpResponse response = httpclient.execute(httppost);

		String result = null;
		BufferedReader in = null;
		in = new BufferedReader(new InputStreamReader(response.getEntity()
				.getContent()));

		StringBuffer sb = new StringBuffer("");
		String line = "";
		String NL = System.getProperty("line.separator");
		while ((line = in.readLine()) != null) {
			sb.append(line + NL);
		}
		in.close();

		result = sb.toString();
		String accountNumber = result.substring(result.indexOf("acc=") + 4,
				result.indexOf("service_rep.jpg") - 31);
		String soDetail = result.substring(
				result.indexOf("colGeneralSymptoms") + 35,
				result.indexOf("Work Perf:") - 69);

		String workPerformed = result.substring(
				result.indexOf("colGeneralResolutions") + 38,
				result.indexOf("<td colspan=2>&nbsp;</td>") - 21);

		String soBlntask = result.substring(
				result.indexOf("colGeneralResolutions") + 38,
				result.indexOf("<td colspan=2>&nbsp;</td>") - 21);

		String strRateBasis = getRateBasis(soNum, accountNumber);

		String[] retString = new String[] { soDetail, workPerformed,
				accountNumber, soBlntask, strRateBasis };
		return retString;
	}

	public String getRateBasis(String soNum, String accountNumber)
			throws IllegalStateException, IOException {
		HttpPost httppost = new HttpPost(serverURL + "editcall2.asp");
		List<NameValuePair> nvp = new ArrayList<NameValuePair>();
		nvp.add(new BasicNameValuePair("sonum", soNum));
		nvp.add(new BasicNameValuePair("accnum", accountNumber));
		// nvp.add(new BasicNameValuePair("accname", accName));
		nvp.add(new BasicNameValuePair("date1", ""));
		nvp.add(new BasicNameValuePair("date2", ""));
		nvp.add(new BasicNameValuePair("source", "reppendingso"));
		httppost.setEntity(new UrlEncodedFormEntity(nvp));
		HttpResponse response = httpclient.execute(httppost);

		String result = null;
		BufferedReader in = null;
		in = new BufferedReader(new InputStreamReader(response.getEntity()
				.getContent()));

		StringBuffer sb = new StringBuffer("");
		String line = "";
		String NL = System.getProperty("line.separator");
		while ((line = in.readLine()) != null) {
			sb.append(line + NL);
		}
		in.close();

		result = sb.toString();
		if (result.contains("Standard")) {
			return "Standard";
		} else {
			return "Account Default";
		}
	}

	public void logOut(String globalURI) throws ClientProtocolException,
			IOException {
		HttpGet httpget = new HttpGet(globalURI + "employeelogin.asp");
		List<NameValuePair> nvp = new ArrayList<NameValuePair>();
		nvp.add(new BasicNameValuePair("logstatus", "out"));
		HttpResponse response = httpclient.execute(httpget);
		String resp = response.toString();
	}

	public boolean loginFailed(HttpResponse response)
			throws IllegalStateException, IOException {

		String result = null;
		BufferedReader in = null;
		in = new BufferedReader(new InputStreamReader(response.getEntity()
				.getContent()));

		StringBuffer sb = new StringBuffer("");
		String line = "";
		String NL = System.getProperty("line.separator");
		while ((line = in.readLine()) != null) {
			sb.append(line + NL);
		}
		in.close();

		result = sb.toString();
		String test = result.substring(228, 250);
		// System.out.println("Value of test=" + test);
		if (test.equals("Invalid Password Entry")) {
			return true;
		}
		return false;
	}

	public String[] getAccountDetail(String accountNumber, String accountName)
			throws ClientProtocolException, IOException {
		// String accountNumber = getAccountNumber(accountName);

		HttpPost httppost = new HttpPost(serverURL + "accountinfo2.asp");
		List<NameValuePair> nvp = new ArrayList<NameValuePair>();
		nvp.add(new BasicNameValuePair("mike", accountNumber));
		nvp.add(new BasicNameValuePair("hidd1", "0"));
		httppost.setEntity(new UrlEncodedFormEntity(nvp));
		HttpResponse response = httpclient.execute(httppost);

		String result = null;
		BufferedReader in = null;
		in = new BufferedReader(new InputStreamReader(response.getEntity()
				.getContent()));

		StringBuffer sb = new StringBuffer("");
		String line = "";
		String NL = System.getProperty("line.separator");
		while ((line = in.readLine()) != null) {
			sb.append(line + NL);
		}
		in.close();

		result = sb.toString();
		// System.out.println(result);
		String concat = result.substring(result
				.indexOf("var contvar = parseInt("));

		String[] resArray = new String[7];
		resArray[0] = concat.substring(23,
				concat.indexOf(")\nif (contvar > 0) {")); // Contact ID number
		String contactName = result.substring(result.indexOf("<option value="
				+ resArray[0])
				+ 15 + resArray[0].length()); // chop the string a bit
		resArray[1] = contactName
				.substring(0, contactName.indexOf("</option>")); // Get the
																	// Contact
																	// Name
		resArray[2] = result.substring(result.indexOf("colCity") + 16,
				result.indexOf("\" size=\"16\"")); // City
		resArray[3] = result
				.substring(
						result.indexOf("colPrimaryPhoneNumberFormatted\' size=16 maxlength=14 tabindex=8 value=\'") + 71,
						result.indexOf("\'><tr>"));
		resArray[4] = result.substring(
				result.indexOf("colAddress1\" size=\"16\" value=\"") + 30,
				result.indexOf("\" maxlength=50 tabindex=11>"));
		resArray[5] = result.substring(
				result.indexOf("</option><option selected>") + 26,
				result.indexOf("</option><option selected>") + 28);
		resArray[6] = result.substring(
				result.indexOf("tabindex=14 value=\'") + 19,
				result.indexOf("tabindex=14 value=\'") + 24);
		String address = resArray[4] + " " + resArray[2] + " " + resArray[5]
				+ " " + resArray[6];

		String[] resultSet = new String[] { accountName, resArray[1],
				resArray[3], address, accountNumber };
		// returned array consists of four elements, account name, contact name,
		// phone number
		// and address
		return resultSet;
	}

	public long addSOLog(String soNumber, String logDetail, String startTime,
			String endTime, String startDate, String endDate, String newStatus,
			String copyToWorkPerformed) {

		return 0;
	}

	public String getAccountNumber(String accountName)
			throws ClientProtocolException, IOException {
		String catAccountName = accountName.replaceAll(" ", "+");
		String url = serverURL + "accountinfo.asp?criteria=" + catAccountName;
		String result = getContent(url);
		String concat = result.substring(result.indexOf("<option value=") + 14,
				result.indexOf(">" + accountName));
		return concat;
	}

	public String getSOtasks() throws ClientProtocolException, IOException {
		HttpPost httppost = new HttpPost(serverURL + "tasks_pending.asp");
		List<NameValuePair> nvp = new ArrayList<NameValuePair>();
		nvp.add(new BasicNameValuePair("sched", "30"));
		httppost.setEntity(new UrlEncodedFormEntity(nvp));
		HttpResponse response = httpclient.execute(httppost);

		String result = null;
		BufferedReader in = null;
		in = new BufferedReader(new InputStreamReader(response.getEntity()
				.getContent()));

		StringBuffer sb = new StringBuffer("");
		String line = "";
		String NL = System.getProperty("line.separator");
		while ((line = in.readLine()) != null) {
			sb.append(line + NL);
		}
		in.close();

		result = sb.toString();

		String[] retString = result.split("Service Order ");
		String resultString = "";

		for (int i = 1; i < retString.length; i++) {
			resultString = resultString.concat(retString[i].substring(0, 7)
					.trim() + " ");
		}

		return resultString;
	}

	public String[] getPrintableSO(String soNum) throws ClientProtocolException, IOException{
		String url = serverURL  + "printcall.asp?field=" + soNum;
		String result = getContent(url);
		result = result.substring(result.indexOf("</script>")+9);
		result = result.substring(result.indexOf("</script>"));
		result = result.replaceAll("</script>", "");
		result = result.trim();
		result = result.substring(0, result.indexOf("<table border=1 width=99%>"));
		result = result.replaceAll("&nbsp;", " ");
		result = result.replaceAll("<br clear=\"all\">", "<br>");
		result = result.replaceAll("<font size=2 face=\"helvetica\"><b>", "");
		result = result.replaceAll("<font size=1 face=\"verdana\">", "");
		result = result.replaceAll("<table width=50% border=0 cellpadding=2 cellspacing=1 align=\"left\">", "");
		result = result.replaceAll("<table width=50% border=0 cellpadding=1 cellspacing=1 align=\"right\">", "");
		result = result.replaceAll("<td colspan=3 width=46% valign=\"top\" align=\"right\"><font size=4 face=\"serif\"><b>", "");
		result = result.replaceAll("<td align=\"right\" width=18%><font size=\"2\" face=\"verdana\"><b>", "");
		result = result.replaceAll("<td align=\"right\" width=28%>", "");
		result = result.replaceAll("<td width=54%>", "");
		result = result.replaceAll("<td align=\"right\"><font size=1 face=\"verdana\">", "");
		result = result.replaceAll("<table width=26% border=0 align=\"left\">", "");
		result = result.replaceAll("<tr><td width=30% nowrap><font size=1 face=\"verdana\">", "");
		result = result.replaceAll("<td width=25% nowrap><font size=1 face=\"verdana\">", "");
		result = result.replaceAll("<td width=12% nowrap><font size=1 face=\"verdana\">", "");
		result = result.replaceAll("<td width=33% nowrap><font size=1 face=\"verdana\">", "");
		result = result.replaceAll("<hr width=\"220\" align=\"center\" size=1 noshade>", "");
		result = result.replaceAll("<table border=0 width=99% cellpadding=2 cellspacing=1>", "");
		result = result.replaceAll("<td colspan=3><font size=1 face=\"verdana\"><b>", "");
		result = result.replaceAll("<td colspan=1><font size=1 face=\"verdana\"><b>", "");
		result = result.replaceAll("<td colspan=1 width=\"20%\"><font size=1 face=\"verdana\"><b>", "");
		result = result.replaceAll("<tr><td colspan=5><font size=1 face=\"verdana\"><b>", "");
		result = result.replaceAll("<table width=\"40%\" border=0 align=\"left\">", "");
		result = result.replaceAll("<table width=34% border=0 align=\"left\">", "");
		result = result.replaceAll("<td width=99%><u>", "");
		result = result.replaceAll("<td width=30% nowrap>", "");
		result = result.replaceAll("<td width=25% nowrap>", "");
		result = result.replaceAll("<td width=12% nowrap>", "");
		result = result.replaceAll("<td width=33% nowrap>", "");
		result = result.replaceAll("<td nowrap>", "");
		result = result.replaceAll("</u>", "");
		result = result.replaceAll("<br>", "");
		result = result.replaceAll("<td>", "");
		result = result.replaceAll("</b>", "");
		result = result.replaceAll("<b>", "");
		result = result.replaceAll("<td align=\"right\">", "");
		result = result.replaceAll("<td colspan=1 width=\"20%\">", "");
		result = result.replaceAll("<td colspan=1>", "");
		result = result.replaceAll("<td colspan=3>", "");
		result = result.replaceAll("<td colspan=5>", "");
		result = result.replaceAll("</td>", "");
		result = result.replaceAll("<tr>", "");
		result = result.replaceAll("</tr>", "");
		result = result.replaceAll("</table>", "");
		result = result.replaceAll("</font>", "");
		result = result.replaceAll(":\n", " : ");
		result = result.replaceAll("Ship-To", "");
		result = result.replaceAll("Work Performed:", "Work Performed:\n");
		result = result.replaceAll("Service Order\n\n\n \n", "Service Order\n");
		result = result.replaceAll("No.\n", "No. ");
		result = result.replaceAll("(?m)^[ \t]*\r?\n", "");
		result = result.replaceAll("<table border=1 cellpadding=1 cellspacing=1>", "");
		result = result.replaceAll("<caption align=\"left\"><u>", "");
		result = result.replaceAll("</caption>", "");
		result = result.replaceAll("<font size=1 face='verdana'>", "");
		result = result.replaceAll("<td colspan=2 bgcolor='#000000'>", "\n");
		result = result.replaceAll("Description:", "");
		result = result.replaceAll("Priority:", "");
		result = result.replaceAll("Status:", "");
		result = result.replaceAll("Taken By:", "");
		result = result.replaceAll("Payment:", "");
		result = result.replaceAll("System:", "");
		result = result.replaceAll("Type:", "");
		result = result.replaceAll("Assigned To:", "");
		result = result.replaceAll("Problem:", "");
		result = result.replaceAll("Work Performed:", "");
		result = result.replaceAll("Directions:", "");
				
		String[] output = result.split("\n");
		return output;
	}
}